package com.lxh.mp.controller;

import com.lxh.mp.utils.JsonUtils;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * created by lanxinghua@2dfire.com on 2020/2/21
 * 公众号网页授权
 *
 * */
@AllArgsConstructor
@Controller
@RequestMapping("/wx/redirect/{appid}")
public class WxRedirectController {
    private static Logger logger = LoggerFactory.getLogger(WxRedirectController.class);
    private final WxMpService wxService;


    /**
     * 授权获取用户信息
     * @param appid
     * @param code
     */
    @RequestMapping("/oauth/callback")
    public void oauth(@PathVariable String appid,
                      @RequestParam String code,
                      @RequestParam String state,
                      HttpServletRequest request,
                      HttpServletResponse response) throws Exception{
        // 切换公众号
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        try {
            // 公众号网页授权获取用户基本信息
            WxMpOAuth2AccessToken accessToken = wxService.oauth2getAccessToken(code);
            WxMpUser user = wxService.oauth2getUserInfo(accessToken, null);
            logger.info("公众号网页授权获取用户基本信息:" + JsonUtils.toJson(user));
            if (StringUtils.isBlank(state)){
                throw new Exception("授权后跳转链接为空");
            }
            HttpSession session = request.getSession();
            session.setAttribute("token", user);
            response.sendRedirect(state);
        } catch (WxErrorException e) {
            logger.error(e.getMessage());
        }
    }


    /**
     * 拆分链接跳转（进行授权）
     * 测试：http://chenxingxing.51vip.biz/wx/redirect/wx62458041039e62ee/split/jump?url=http://chenxingxing.51vip.biz
     * @param appid
     * @param url
     */
    @RequestMapping("/split/jump")
    public void jump(@PathVariable String appid,
                     @RequestParam String url,
                     HttpServletResponse response) throws Exception{
        if (StringUtils.isBlank(url)){
            throw new Exception("url为空");
        }
        // 切换公众号
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        String authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=%s#wechat_re";
        String oauthCallbackUrl = "http://chenxingxing.51vip.biz/wx/redirect/%s/oauth/callback";
        oauthCallbackUrl = String.format(oauthCallbackUrl, appid);
        authUrl = String.format(authUrl, appid, oauthCallbackUrl, url);
        // 构建授权url
        // https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx62458041039e62ee&redirect_uri=http://chenxingxing.51vip.biz/wx/redirect/wx62458041039e62ee//oauth/callback&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_re
        logger.info("授权url：" + authUrl);
        response.sendRedirect(authUrl);
    }


    /**
     * 创建js-sdk签名
     * @param url
     * @return
     * @throws Exception
     */
    @RequestMapping("/create/jsapi_sign")
    @ResponseBody
    public Object jssdk(@PathVariable String appid,
                        @RequestParam  String url) throws Exception{
        // 切换公众号
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        logger.info("url:" + url);
        WxJsapiSignature jsapiSignature = wxService.createJsapiSignature(url);
        return jsapiSignature;
    }
}
